package com.jingjin.userservice.util.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * ClassName: EmailUtil
 * Description: 邮箱发送操作工具类
 *
 * @Author zjm
 */
@Component
@RefreshScope
@Slf4j
public class EmailUtil {

    /**
     * 邮箱账号
     */
    @Value("${auth.email.account:''}")
    private String account;

    /**
     * 邮箱对应使用的密码
     */
    @Value("${auth.email.password:''}")
    private String password;

    public Boolean sendMessage(String email, String title, String context) throws Exception {
        //创建Session对象
        Session session = createSession(account, password);
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        message.setSubject(title); //设置邮件标题
        message.setText(context); //设置邮件内容
        message.setFrom(new InternetAddress(account)); //设置发件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); //设置收件人

        //发送
        Transport.send(message);
        return true;
    }

    public static Session createSession(String account, String password) {

        // SMTP服务器连接信息
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true"); // 启用 SSL
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");

        //创建Session会话
        //参数1：smtp服务器连接参数
        //参数2：账号密码的授权认证对象
        return Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(account, password);
            }
        });
    }
}
